<!--
 * @Author: 袁十一
 * @Date: 2023-10-06 14:42:15
 * @LastEditTime: 2023-10-17 16:24:39
 * @LastEditors: Please set LastEditors
 * @Description: 
 * @FilePath: \Vue3_admin_template\src\views\product\trademark\index.vue
 * 初心不变，意志坚定
-->
<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" icon="plus" @click="addTradeMark">
        添加品牌
      </el-button>
      <el-table style="width: 100%; margin: 10px 0" border :data="tabledata">
        <el-table-column
          type="index"
          label="序号"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column prop="address" label="品牌logo">
          <template #="{ row }">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="品牌操作">
          <template #="{ row }">
            <el-button
              icon="Edit"
              type="warning"
              @click="updateTradeMark(row)"
            ></el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="你确定要删除吗？"
              @confirm="confirmEvent(row.id)"
              width="200px"
            >
              <template #reference>
                <el-button icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        layout=" prev, pager, next, jumper,->,total, sizes"
        :total="total"
        background
        @current-change="HasTradeData"
        :pager-count="5"
        @size-change="pagechange"
      ></el-pagination>
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarksParams.id ? '修改品牌' : '添加品牌'"
      style="width: 700px"
    >
      <el-form
        style="width: 80%"
        :model="trademarksParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            autocomplete="off"
            style="width: 300px"
            v-model="trademarksParams.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarksParams.logoUrl"
              :src="trademarksParams.logoUrl"
              class="avatar"
              style="width: 250px; height: 250px"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  deleteTrademark,
} from '@/api/product/trademark/index'
import {
  Records,
  TradeData,
  TradeObjectData,
} from '@/api/product/trademark/type'
import { ElMessage, UploadProps } from 'element-plus'
// 当前页码
let pageNo = ref<number>(3)
// 一页显示数据条数
let limit = ref<number>(3)
// 总共多少商品
let total = ref<number>(0)
// 商品数据
let tabledata = ref<Records>([])
// 控制对话框是否显示
let dialogFormVisible = ref<boolean>(false)
// 获取已有品牌数据方法
const HasTradeData = async (pager = 2) => {
  pageNo.value = pager
  let result: TradeData = await reqHasTrademark(pageNo.value, limit.value)
  // console.log(result);
  if (result.code == 200) {
    pageNo.value = result.data.current
    limit.value = result.data.size
    total.value = result.data.total
    tabledata.value = result.data.records
  }
}
// 页面挂载
onMounted(() => {
  HasTradeData()
})
// 分页器当前数据发生变化的时候再次发请求获取已有品牌的数据
const pagechange = () => {
  pageNo.value = 2
  HasTradeData()
}
const cancel = () => {
  dialogFormVisible.value = false
}

// 定义收集品牌数据
let trademarksParams = reactive<TradeObjectData>({
  tmName: '',
  logoUrl: '',
})
// 上传文件之前调用
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件必须是JPEG/PNG/GIF',
    })
  }
}
// 图片上传成功勾子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  // console.log(response, uploadFile);
  trademarksParams.logoUrl = response.data
  // 图片上传成功清理掉提示信息
  formRef.value.clearValidate('logoUrl')
}
// 获取Form表单实例对象
let formRef = ref<any>()
// 表单校验的自定义方法
// 品牌名校验自定义方法
const validatorTmName = (_rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称长度必须大于2'))
  }
}
// 品牌LOGO校验自定义方法
const validatorLogoUrl = (_rule: any, value: any, callBack: any) => {
  if (value) {
    // 放行
    callBack()
  } else {
    callBack(new Error('请上传品牌图片'))
  }
}
// 定义表单校验对象
const rules = {
  tmName: [
    // required表单是必须要校验的，效果表单项前面出现一个五角星
    // trigger表单校验出现的时机，blur表单项失去焦点是触发
    // validator表单校验的自定义方法
    { required: true, trigger: 'blur', validator: validatorTmName },
  ],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}
// 点击添加按钮触发，控制弹窗
const addTradeMark = async () => {
  // 清空数据
  trademarksParams.id = undefined
  trademarksParams.logoUrl = ''
  trademarksParams.tmName = ''
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

// 修改已有品牌数据
const updateTradeMark = (row: TradeObjectData) => {
  dialogFormVisible.value = true
  trademarksParams.id = row.id
  trademarksParams.logoUrl = row.logoUrl
  trademarksParams.tmName = row.tmName
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
// 添加/修改品牌
const confirm = async () => {
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(trademarksParams)
  if (result.code == 200) {
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: result.message,
    })
    // 重新获取品牌信息
    HasTradeData()
  } else {
    ElMessage({
      type: 'error',
      message: result.message,
    })
    dialogFormVisible.value = false
  }
}
// 删除品牌
const confirmEvent = async (id: number) => {
  let result: any = await deleteTrademark(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: result.message,
    })
  } else {
    ElMessage({
      type: 'error',
      message: result.message,
    })
  }
  HasTradeData(tabledata.value.length > 1 ? pageNo.value : pageNo.value - 1)
}
</script>

<style scoped>
.avatar-uploader-icon {
  width: 250px;
  height: 250px;
  border: 1px solid #c7c6c6;
}

.avatar-uploader-icon:hover {
  border-color: rgb(96, 152, 236);
}
</style>
